<template>
  <div class="flexContent">
    <h3>分录信息</h3>
    <div class="top">
      <div class="rows">
        <span class="col">
          <div class="txt">分录仓库:</div>
          <el-select v-model="warehouseId" popper-class="eloption" placeholder="请选择">
            <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </span>
        <span class="col">
          <div class="txt">门店名称:</div>
          <span>{{ storeDetails.name }}</span>
        </span>
        <span class="col">
          <div class="txt">门店地址:</div>
          <span>{{ storeDetails.address }}</span>
        </span>
      </div>
      <div class="rows">
        <span class="col">
          <div class="txt">点采金额:</div>
          <span>{{ commodityAmount }}元</span>
        </span>
        <span class="col">
          <div class="txt">分录日期:</div>
          <span>
            <span v-for="(item, index) in storeDetails.entriesDays" :key="index" class="dateClass">{{ item |
              fileTime(dayList) }}</span>
          </span>
        </span>
      </div>
      <!-- <div class="rows">
        <span class="col" style="width: 100% !important;">
          <div class="txt">点采编号:</div>
          <span class="pickList">
            <span v-for="item in pickLists" :key="item" class="pickListItem">{{
              item
            }}</span>
          </span>
        </span>
      </div> -->
      <div style="display: flex; flex-wrap: wrap">
        <span>点采编号：</span><span v-for="item in pickLists" :key="item"
          style="margin-right: 20px; word-wrap: break-word">{{ item }}</span>
      </div>
    </div>
    <div class="add">
      <el-button class="addBtn" :disabled="!warehouseId" @click="getStoreOrderList">调点采</el-button>
      <el-button class="addBtn" v-if="tableData.length > 0" @click="exportOrder">导出</el-button>
    </div>
    <div class="table">
      <div>
        <el-table border class="tablebox" :data="tableData" max-height="462px" size="medium" :cell-style="tableCellStyle">
          <el-table-column label="序号" type="index" align="center" width="80" />
          <el-table-column label="商品名称" prop="commodityName" align="center" />
          <el-table-column label="商品条码" prop="barCode" align="center" />
          <el-table-column align="center" label="规格" prop="commodityStandard" />
          <el-table-column align="center" label="单位" prop="commodityUnit" />
          <el-table-column align="center" label="产地" prop="commodityProducer" />
          <el-table-column align="center" label="数量" prop="procureCount" />
          <el-table-column align="center" label="现有库存" prop="inventoryNum" />
          <el-table-column align="center" label="在途库存" prop="transitNum" />
        </el-table>
      </div>
    </div>
    <div class="returnBtn">
      <el-button class="celBtn" @click="returnList">返 回</el-button>
      <el-button class="addBtn" @click="definiteEntryFn">确 定</el-button>
    </div>
    <!-- @select-all="selFn"
    @select="selFn" -->
    <el-dialog title="调点采" :visible.sync="dialogTableVisible">
      <h3>调点采</h3>
      <el-table border :data="gridData1" ref="multipleTable" class="tablebox" height="202px" @row-click="handlerClick"
        @selection-change="selFn" size="medium">
        <el-table-column type="selection" align="center" width="55" />
        <el-table-column property="pickNumber" align="center" label="点采编号" />
        <el-table-column property="pickTime" align="center" label="点采时间">
          <template v-slot="{ row }">
            <span>{{ row.pickTime | parseTime }}</span>
          </template>
        </el-table-column>
      </el-table>
      <h3 style="padding-top: 30px">点采明细</h3>
      <el-table border :data="gridData2" class="tablebox" height="202px" size="medium">
        <el-table-column type="index" align="center" label="序号" width="80" />
        <el-table-column property="commodityName" align="center" label="商品名称" />
        <el-table-column property="commodityStandard" align="center" label="规格" />
        <el-table-column property="commodityUnit" align="center" label="单位" />
        <el-table-column property="commodityProducer" align="center" label="产地" />
        <el-table-column property="procureNumber" align="center" label="件数(配送规格)" />
        <el-table-column property="procureCount" align="center" label="数量" />
        <el-table-column property="commodityBrand" align="center" label="品牌" />
      </el-table>
      <div slot="footer">
        <el-button class="celBtn" @click="cancelFn">取消</el-button>
        <el-button class="addBtn" @click="confirmFn">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { print, checkPrinter } from "@/utils/printLODOP";
import FileSaver from 'file-saver'
import { getShopDetail } from "@/api/shop";
import {
  getWarehouseList,
  getStorePickUpOrder,
  getStorePickUpOrderDetail,
  addStorePickUpOrder,
  definiteEntry,
  exportOrder,
} from "@/api/entrycenter";
export default {
  name: "EntryCenterSetting",
  data() {
    return {
      storeDetails: {},
      warehouseList: [],
      tableData: [],
      gridData1: [],
      gridData2: [],
      pickList: [],
      pickLists: [],
      pickId: "",
      dialogTableVisible: false,
      id: "",
      warehouseId: "",
      commodityAmount: 0,
      // warehouseName: '',
      dayList: {
        1: "周一",
        2: "周二",
        3: "周三",
        4: "周四",
        5: "周五",
        6: "周六",
        7: "周日",
      },

      // 打印数据数组
      printArray: [],
    };
  },
  created() {
    this.id = this.$route.query.id ? this.$route.query.id : "";
    this.getShopDetail();
    this.getWarehouseList();
  },
  methods: {
    async getShopDetail() {
      const res = await getShopDetail({ id: this.id });
      if (res.code === 200) {
        console.log(res.data, "门店详情");
        this.storeDetails = res.data.store;
      }
    },
    async getWarehouseList() {
      const res = await getWarehouseList();
      if (res.code === 200) {
        this.warehouseList = res.data;
        if (this.warehouseList.length === 0) {
          this.warehouseId = "";
          this.$message.warning("暂无仓库");
          return;
        }
        this.warehouseId = this.warehouseList[0].id;
        // this.warehouseName = this.warehouseList[0].name
        console.log(this.warehouseList, "仓库列表");
      }
    },
    returnList() {
      this.closeTag("entrycenter");
    },
    cancelFn() {
      this.dialogTableVisible = false;
    },
    // 获取点采订单
    async getStoreOrderList() {
      this.dialogTableVisible = true;
      const res = await getStorePickUpOrder({
        entryStatus: "0",
        storeId: this.id,
      });
      if (res.code === 200) {
        console.log(res.data, "点采订单");
        this.gridData1 = res.data;
      }
    },
    handlerClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row);
    },
    async selFn(selection) {
      this.gridData2 = [];
      // console.log(selection, row, 'selection')
      this.pickList = selection.map((item) => item.pickNumber);
      console.log(this.pickList, "this.pickList");
      this.pickId = this.pickList[this.pickList.length - 1];
      console.log(this.pickId, "this.pickId");
      if (this.pickId) {
        const res = await getStorePickUpOrderDetail({
          storeId: this.id,
          pickNumber: this.pickId,
          submitStatus: "1",
        });
        if (res.code === 200) {
          this.gridData2 = res.data;
          console.log(this.gridData2, "this.gridData2");
        }
      }
    },
    async confirmFn() {
      if(this.pickList.length === 0) return this.$message.warning('请选择点采单')
      const res = await addStorePickUpOrder({
        pickList: this.pickList,
        warehouseId: this.warehouseId,
      });
      if (res.code === 200) {
        // console.log(res.data, "@@@@@@@@");
        this.pickLists = this.pickList.map((item) => item);
        // console.log(rsaDecrypt(res.data), '解密')
        this.dialogTableVisible = false;
        this.gridData2 = [];
        // this.$message.success('提交成功')
        this.tableData = res.data.storeRequireVoList;
        console.log(this.tableData, "this.tableData");
        this.commodityAmount = res.data.commodityAmount;
      }
    },
    tableCellStyle(data){
      console.log('row,colum',data);
      if(data.column.property === 'inventoryNum') {
        if(data.row.inventoryNum === 0){
          return "background: #f31717;color: #fff";
        }else if(data.row.inventoryNum < data.row.procureCount){
          return "background: #dd5828;color: #fff";
        }
      }
    },
    async definiteEntryFn() {
      // print(this.printArray);
      // console.log(333333);
      // return ;
      let hasPrinter = checkPrinter();
      if (this.pickLists.length === 0)
        return this.$message.warning("请选择点采单");
      let hasZero = this.tableData.some(item => item.procureCount > item.inventoryNum || item.inventoryNum <= 0);
      if (hasZero) {
        this.$confirm(`有商品库存不足,是否继续分录?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const res = await definiteEntry({
            storeId: this.id,
            warehouseId: this.warehouseId,
            pickList: this.pickLists,
          });
          if (res.code === 200) {
            this.printArray = res.data.chooseOrderVoList;
            if (hasPrinter) {
              print(this.printArray);
            }
            console.log(res.data, "成功");
            this.$message.success("分录成功,拣货单正在打印");
            this.closeTag("entrycenter");
          } else if (res.code === 76001) {
            this.$alert(res.message, "错误", {
              type: "error",
              confirmButtonText: "返回",
            }).then(() => {
              this.closeTag("entrycenter");
            });
          } else {
            // this.$message.error(res.message)
          }
        }).catch(()=>{
          
        })
      }else {
        const res = await definiteEntry({
            storeId: this.id,
            warehouseId: this.warehouseId,
            pickList: this.pickLists,
          });
          if (res.code === 200) {
            this.printArray = res.data.chooseOrderVoList;
            if (hasPrinter) {
              print(this.printArray);
            }
            console.log(res.data, "成功");
            this.$message.success("分录成功,拣货单正在打印");
            this.closeTag("entrycenter");
          } else if (res.code === 76001) {
            this.$alert(res.message, "错误", {
              type: "error",
              confirmButtonText: "返回",
            }).then(() => {
              this.closeTag("entrycenter");
            });
          } else {
            // this.$message.error(res.message)
          }
      }
    },
    exportOrder(){
      this.$confirm('确认导出数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        if(this.pickList.length === 0) return this.$message.warning('请选择点采单')
        const response = await exportOrder({
          pickList: this.pickList,
          warehouseId: this.warehouseId,
        })
        let res = null;
        if (response.data.type === "application/json") {
          const reader = new FileReader();  //创建一个FileReader实例
          reader.readAsText(response.data, 'utf-8'); //读取文件,结果用字符串形式表示
          reader.onload = () => {//读取完成后,**获取reader.result**
            res = JSON.parse(reader.result)
            if (res.code !== 200) {
              this.$message.error(res.message);
              return;
            }
          }
        } else {
          const fileName = decodeURIComponent(response.headers["content-disposition"].split(";")[1].split("''")[1]);
          FileSaver.saveAs(response.data, fileName);
        }
      })
    }
  },
};
</script>

<style lang="scss" scoped>
.flexContent {
  h3 {
    margin: 0;
    margin-bottom: 10px;
  }

  .top {
    padding-bottom: 10px;

    .rows {
      display: flex;
      margin-bottom: 10px;
      min-height: 40px;
      line-height: 40px;

      .col {
        width: 33%;
        display: flex;
        padding-right: 10px;
        vertical-align: middle;

        .txt {
          width: 80px;
        }

        .dateClass {
          padding: 0 5px;
          display: inline-block;
          margin-right: 5px;
          background-color: rgb(113, 113, 240);
          color: #fff;
          font-size: 12px;
          border-radius: 3px;
          margin-bottom: 5px;
        }

        .pickList {
          display: flex;
          flex: 1;
          flex-wrap: wrap;

          .pickListItem {
            flex: 1;
            height: 30px;
            padding: 0 5px;
            margin-bottom: 5px;
            font-size: 12px;
          }
        }
      }
    }
  }
}
</style>
